package indi.youxiaozhong.http;

import android.content.Context;
import android.util.Log;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Map;


public class VelocityUtils {

    private final String ftlPath;

    private Context context;

    private VelocityEngine ve;

    private static VelocityUtils self;

    protected static void init(Context context) throws  IOException{
        self = new VelocityUtils(context);
    }

    public static String toHtml(String ftlPath,Map<String,Object> data)throws IOException{
           return self._toHtml(ftlPath,data);
    }

    private VelocityUtils(Context context) throws IOException{
        this.context = context;
        ftlPath = context.getFilesDir().getAbsolutePath()+"/template";

        ve=new VelocityEngine();

        //ve.setProperty(Velocity.RESOURCE_LOADER, ftlPath);

        File dir = new File(ftlPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        ve.init();

    }


    private String _toHtml(String path, Map<String,Object> data)throws IOException {


        InputStream is = context.getAssets().open(path);

        File file = new File(ftlPath + "/" + path);
        File dir = file.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }


        FileOutputStream fos = new FileOutputStream(file);
        byte[] buffer = new byte[7168];
        int count = 0;
        while ((count = is.read(buffer)) > 0) {
            fos.write(buffer, 0, count);
        }

        fos.flush();
        fos.close();
        is.close();

        Template tmp =  ve.getTemplate(file.getAbsolutePath());

        StringWriter out = new StringWriter();
        try {
            VelocityContext context = new VelocityContext();

            if(data!=null) {
                for (Map.Entry<String, Object> entry : data.entrySet()) {
                    //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                    context.put(entry.getKey(), entry.getValue());
                }
            }

            tmp.merge(context, out);

        }catch (Exception e){
            e.printStackTrace();
            out.close();
        }finally {
            out.close();
        }


        String html =  out.toString();
        Log.i("velocity",html);
        return html;


    }



}
